package v1

import (
	"blog/model"
	"blog/model/response"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 添加分类
func AddCategory(c *gin.Context) {
	var category model.Category
	_ = c.ShouldBindJSON(&category)
	code := model.CheckCategory(category.Name)
	if code == response.SUCCESS {
		model.CreateCategory(&category)
	}
	c.JSON(
		http.StatusOK, gin.H{
			"status":  code,
			"message": response.GetMessage(code),
			"data":    category,
		},
	)

}

//查询分类
func GetCategories(c *gin.Context) {
	pageSize, _ := strconv.Atoi(c.Query("pageSize"))
	pageNum, _ := strconv.Atoi(c.Query("pageNum"))
	if pageSize == 0 {
		pageSize = -1
	}
	code := response.SUCCESS
	categories, total := model.GetCategories(pageSize, pageNum)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"data":    categories,
		"total":   total,
		"message": response.GetMessage(code),
	})
}

//编辑分类
func EditCategory(c *gin.Context) {
	var category model.Category
	id, _ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&category)
	code := model.CheckCategory(category.Name)
	if code == response.SUCCESS {
		model.EditCategory(id, &category)
	}
	if code == response.ERROR_CATENAME_USED {
		c.Abort()

	}
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}

// 删除分类
func DeleteCategory(c *gin.Context) {
	id, _ := strconv.Atoi(c.Param("id"))
	code := model.DeleteCategory(id)
	c.JSON(http.StatusOK, gin.H{
		"status":  code,
		"message": response.GetMessage(code),
	})
}
